<template>
  <div class="app-container" style="padding:8px 0px 10px 0px;height: calc(100% - 50px);">
    <el-form ref="showParamsRef" :inline="true" :model="queryParams" label-width="65px">
      <el-row style="margin-top: -10px;margin-bottom: -15px;">
        <el-form-item label="选择患者" prop="itemName">
          <bed-vs-patient-into-select :bed-blank="'Y'" :org-id="userInfo.orgId"
                                      :visit-id="queryParams.visitId"
                                      :ward-code="currentSelectDept" class="width-120"
                                      @bed-change="bedChange"/>
        </el-form-item>
        <el-form-item label="长/临:" prop="repeatIncaditor">
          <el-radio-group v-model="queryParams.repeatIncaditor" @change="handleQuery">
            <el-radio-button label="全部" value=""/>
            <template v-for="(tag, index) in dictDataMap['order_type']">
              <el-radio-button :label="tag.dictLabel" :value="tag.dictValue"/>
            </template>
          </el-radio-group>
        </el-form-item>
        <!--                <el-form-item label="医嘱状态:" prop="orderStatus">-->
        <!--                    <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">-->
        <!--                        <el-radio-button label="全部" value=""/>-->
        <!--                        <template v-for="(tag, index) in dictDataMap['order_status']">-->
        <!--                            <el-radio-button v-if="tag.dictValue != '1'" :label="tag.dictLabel" :value="tag.dictValue"/>-->
        <!--                        </template>-->
        <!--                    </el-radio-group>-->
        <!--                </el-form-item>-->
        <el-form-item label="医嘱内容:" prop="orderText">
          <el-input v-model="queryParams.orderText" class="width-120" clearable
                    placeholder="请输入医嘱内容" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="下达时间:" prop="admissionTime">
          <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                          range-separator="截止" start-placeholder="开始日期" type="daterange"
                          @change="admissionTimeChange"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button class="mb5" style="float: right" type="primary" @click="handleQuery">
            <template #icon>
              <i-ep-search/>
            </template>
            刷新
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-row v-if="isShowQuery" class="mb5">
      <el-col :span="12">
        <template v-if="configPersonIsOneTouchOrder.configValue ==='Y'">
          <el-tooltip class="box-item" content="转抄【传输】状态的医嘱，校对【长期】【临时】医嘱，并执行【临时】医嘱"
                      effect="dark" placement="bottom">
            <el-button class="ml10" type="primary" @click="executeOrder">
              <svg-icon class="mr5" icon-class="execute"/>
              转抄并执行(F1)
            </el-button>
          </el-tooltip>
          <el-tooltip class="box-item" content="操作【医生停止】的【长期】医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" type="danger" @click="stopOrder">
              <svg-icon class="mr5" icon-class="stop"/>
              转抄并停止(F8)
            </el-button>
          </el-tooltip>
        </template>
        <template v-else>
          <el-tooltip class="box-item" content="操作【传输】状态的医嘱" effect="dark" placement="bottom">
            <el-button class="ml10" type="warning" @click="orderTranscribe">
              <svg-icon class="mr5" icon-class="orderTranscribe"/>
              转抄
            </el-button>
          </el-tooltip>
        </template>
        <el-tooltip class="box-item" content="驳回" effect="dark" placement="bottom">
          <el-button class="ml10" color="#fd7de4" @click="orderReject">
            <svg-icon class="mr5" icon-class="orderReject"/>
            驳回
          </el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <el-table v-adaptive="600" :border="true" :data="orderDialogList" :header-cell-style="$headerCellStyle"
              :stripe="true"
              highlight-current-row @selection-change="handleSelectionChangeDialog">
      <el-table-column :align="'center'" type="selection" width="40"/>
      <el-table-column :align="'center'" fixed="left" label="患者信息" prop="name"
                       width="130">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.name }}</span>
          <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
          {{ scope.row.ageAll }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="医嘱状态" prop="orderStatus" width="90">
        <template #default="scope">
          <template v-for="(tag, index) in dictDataMap['order_status']">
            <template v-if="scope.row.orderStatus.includes(tag.dictValue)">
              <el-button v-if="!tag.cssClass" :class="scope.row.orderStatus === '1' ? 'mb25': ''"
                         :type="tag.listClass"
                         style="border: 1px #000000 solid">{{ tag.dictLabel }}
              </el-button>
              <el-button v-else :class="scope.row.orderStatus === '1' ? 'mb25': ''" :color="tag.cssClass"
                         style="border: 1px #000000 solid">{{ tag.dictLabel }}
              </el-button>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="是否计价" prop="billingAttr" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['billing_attr']"
                         :value="scope.row.billingAttr"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="下达时间" prop="createTime" width="140">
        <template #default="scope">
          {{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </template>
      </el-table-column>
      <el-table-column :align="'left'" fixed="left" label="医嘱类别" prop="orderClass" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['new_order_type']"
                         :value="scope.row.orderClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="长/临" prop="repeatIncaditor" width="60">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['order_type']"
                         :value="scope.row.repeatIncaditor"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" fixed="left"
                       label="医嘱内容"
                       prop="orderText"
                       width="200">
        <template #default="scope">
          {{ scope.row.groupNumberStyle }}<span class="ml5">{{
            scope.row.orderText
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="是否医保" prop="isMedical" width="70">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']"
                         :value="scope.row.isMedical"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="途径" prop="channel" width="100">
        <template #default="scope">
          {{ scope.row.channelName }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="频次" prop="performFreq" width="100">
        <template #default="scope">
          {{ scope.row.performFreqName }}
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :header-align="'center'" :show-overflow-tooltip="true" label="执行时间"
                       prop="nursePerformTime" width="100">
        <template #default="scope">
          {{ scope.row.nursePerformTime }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次用量" prop="numSingle" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.numSingle).toFixed(2) }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单次剂量" prop="singleDosage" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ parseFloat(scope.row.singleDosage).toFixed(2) }}<dict-data-tag
                      :options="dictDataMap['dose_unit']" :value="scope.row.doseUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" prop="sumNum" width="90">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ scope.row.sumNum }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.unit"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>

      <el-table-column :align="'center'" label="首日是否摆药" prop="firstDayIsDisp" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']"
                         :value="scope.row.firstDayIsDisp"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="首日摆药数量" prop="firstDayDrugDispAmount" width="100">
        <template #default="scope">
                    <span style="margin-left: -15px"> {{ scope.row.firstDayDrugDispAmount }}<dict-data-tag
                      :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                      style="margin: -23px -20px 0px 35px"/></span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="滴速" prop="dripSpeed" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_drop_speed']"
                         :value="scope.row.dripSpeed"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="执行科室" prop="implementDept" width="100">
        <template #default="scope">
          {{ scope.row.implementDeptName }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="医嘱说明" prop="remarks" width="120">
        <template #default="scope">
          {{ scope.row.remarks }}
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="开单医生" prop="applyUserName" width="90"/>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="90"/>
      <el-table-column :align="'center'" label="校对时间" prop="checkTime" width="140"/>
      <el-table-column :align="'center'" label="校对护士" prop="checkNurseName" width="90"/>
      <el-table-column :align="'center'" label="执行护士" prop="executeNurseName" width="90"/>
      <el-table-column :align="'center'" label="医生停止时间" prop="stopInTime" width="140"/>
      <el-table-column :align="'center'" label="护士停止时间" prop="nurseStopTime" width="140"/>
      <el-table-column :align="'center'" label="停止护士" prop="stopNurseName" width="90"/>
      <el-table-column :align="'center'" label="皮试结果" prop="skinResult" width="90"/>
      <el-table-column :align="'center'" label="签名医生" prop="doctorSignature" width="90"/>
      <el-table-column :align="'center'" label="停止摆药" prop="dispStatus" width="70"/>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import {listOrders, updateOrderStatus} from "@/api/orders/orders.ts"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";


const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('order_status', 'billing_attr', 'order_type', 'new_order_type',
  'sys_yes_no', 'spec_unit', 'sys_drop_speed', 'drug_classification', 'dose_unit', 'sys_user_sex'))

const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref<any>([]);
const props = defineProps({
  visitId: {
    type: String,
    default: ""
  },
  patientId: {
    type: String,
    default: "",
  },
  orderStatus: {
    type: String,
    default: "2",
  },
  isShowQuery: {
    type: Boolean,
    default: true
  }
})
const queryParams = ref<any>({
  repeatIncaditor: "",
  orderStatus: props.orderStatus,
  visitId: props.visitId
})
const ids = ref([]);
const configPersonIsOneTouchOrder = ref<any>({})
const selectionThis = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const orderDialogList = ref<any>([])

const emits = defineEmits(["selectOk"])

function admissionTimeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/**
 * 转抄
 */
function orderTranscribe() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "3"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄成功")
      getList()
      emits("selectOk")
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 转抄并执行
 */
function executeOrder() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】的医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄并执行】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "47"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄并执行成功")
      getList()
      emits("selectOk")
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 转抄并停止
 */
function stopOrder() {
  initSelectionThis("0", "9")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【医生停止】状态的【长期】医嘱，请勾选医嘱状态为【医生停止】的【长期】医嘱后操作。")
  }
  ElMessageBox.confirm("确认要进行【转抄并停止】吗", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      ids: ids.value,
      statusType: "35"
    }
    updateOrderStatus(data).then(() => {
      ElMessage.success("转抄并停止成功")
      getList()
      emits("selectOk")
    })
  }).catch(() => {
    ElMessage.info("取消操作");
  });
}

/**
 * 驳回
 */
function orderReject() {
  initSelectionThis("", "2")
  if (ids.value.length <= 0) {
    return ElMessage.error("未勾选【传输】状态的医嘱，请勾选状态为【传输】状态的医嘱后操作。")
  }
  ElMessageBox.prompt('驳回说明', '确认要进行【驳回】吗', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\S+$/,
    inputErrorMessage: '驳回理由不能为空',
  })
    .then(({value}) => {
      const data = {
        ids: ids.value,
        statusType: "8",
        rebuteRemarks: value
      }
      updateOrderStatus(data).then(() => {
        ElMessage.success("驳回成功")
        getList()
        emits("selectOk")
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}


/**
 * 组织多选功能 向后台传递的ids
 * @param repeatIncaditor 长期/临时
 * @param type 医嘱状态
 */
function initSelectionThis(repeatIncaditor: string, type: string) {
  let thisList = [] as any
  thisList = selectionThis.value.filter((item: any) => item.orderStatus === type)
  // type = 07（校对状态的长期医嘱）
  if (repeatIncaditor + type === '07') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '0')
  }
  // type = 17（校对状态的临时医嘱） （获取状态为校对的临时医嘱）
  if (repeatIncaditor + type === '17') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '1')
  }
  // type = 09 （获取状态为医生停止的长期医嘱）
  if (repeatIncaditor + type === '09') {
    thisList = thisList.filter((item: any) => item.repeatIncaditor === '0')
  }
  ids.value = thisList.map((item: any) => item.id);
}

// 多选框选中数据
function handleSelectionChangeDialog(selection) {
  selectionThis.value = selection
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleQuery() {
  getList()
}

function getList() {
  const param = {
    orgId: userInfo.orgId,
    visitId: queryParams.value.visitId,
    orderText: queryParams.value.orderText,
    repeatIncaditor: queryParams.value.repeatIncaditor,
    orderStatusNotInArray: ['1'],
    orderStatus: props.orderStatus
  }
  listOrders(proxy.$addDateRange(param, dateRange.value)).then((res: resType) => {
    let unsave = orderDialogList.value.filter(e => e.id == null)
    orderDialogList.value = []
    const data: any = res.data
    data.forEach((item: any) => {
      item.doseUnitsName = dictStore.getMateDictInfo(dictDataMap.value['dose_unit'], item.doseUnits).dictLabel
      const unit = item.packSize === "1" ? item.minUnits : item.packageUnits
      item.unit = unit
      item.unitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], unit).dictLabel
      item.minUnitsName = dictStore.getMateDictInfo(dictDataMap.value['spec_unit'], item.minUnits).dictLabel
      item.orderClassDisabled = item.orderClass === '4' || item.orderClass === '5'
      let price: number = 0;
      if (item.ordersCostVoList != null) {
        item.ordersCostVoList.forEach(orderCost => {
          price += Number(orderCost.price)
        })
      }
      item.price = price
      orderDialogList.value.push(item)
      selectionThis.value = []
    })
    orderDialogList.value = orderDialogList.value.concat(unsave)
    unsave = []
  })
}

/**
 * 个人参数 是否一键执行医嘱
 */
function getConfigPersonIsOneTouchOrder() {
  let configPersonIndex = useUserStore.user.configPersonList.findIndex((configPerson: any) => {
    return configPerson.configKey === "is_one_touch_order"
  })
  if (configPersonIndex > -1) {
    configPersonIsOneTouchOrder.value = useUserStore.user.configPersonList[configPersonIndex]
  }
}


/**
 * 切换患者select 点击事件
 * @param obj
 */
function bedChange(obj) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  getList()
}

function clearQueryParams() {
  queryParams.value.repeatIncaditor = ""
  queryParams.value.orderStatus = props.orderStatus
}

getConfigPersonIsOneTouchOrder()
getList()

defineExpose({
  getList,
  clearQueryParams
})
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

:deep(.el-input__wrapper .el-input__inner) {
  margin-right: -15px;
}

:deep(.el-form-item__content) {
  margin-bottom: 6px;
}

:deep(.el-form-item__error) {
  font-size: 11px;
  color: #ff0000;
}

:deep(.el-button--small) {
  --el-button-size: 20px;
}

:deep(.el-table__body tr.current-row>td>div>button>span ) {
  color: #000000 !important;
}


</style>
